<?php

namespace admin\modules\buildingOrder\models\searches;

use yii\db\ActiveQuery;
use common\components\wajaxcrud\generators\crud\SpecialFilterTrait;
use yii\data\ActiveDataProvider;
use common\components\wtools\tools\ArrayHelper;
use admin\models\db\BuildingOrders as BuildingOrdersModel;

/**
 * BuildingOrders represents the model behind the search form about `admin\models\db\BuildingOrders`.
 */
class BuildingOrders extends BuildingOrdersModel
{
    use SpecialFilterTrait;

    const SCENARIO_EDITABLE = 'editable';

    public function rules()
    {
        return [
            [['id', 'status', 'province_id', 'city_id', 'county_id', 'address', 'created_by_admin', 'updated_by_admin', 'title', 'custom_name', 'custom_mobile'], 'safe'],
            [['created_at', 'updated_at', 'deleted_at'], 'match', 'pattern' => '/^.+\s\-\s.+$/'],
        ];
    }

    public function scenarios()
    {
        return ArrayHelper::merge(parent::scenarios(), [
            self::SCENARIO_EDITABLE => [''],
        ]);
    }

    /**
     * Creates data provider instance with search query applied
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = self::find();
        $this->load($params);
        $this->fieldFilter($query, 'id');
        $this->rangeFilter($query, 'created_at', true);
//        $this->rangeFilter($query, 'updated_at', true);
        $this->fieldFilter($query, 'status');
//        $this->rangeFilter($query, 'deleted_at', true);
//        $this->fieldFilter($query, 'province_id');
//        $this->fieldFilter($query, 'city_id');
//        $this->fieldFilter($query, 'county_id');
//        $this->fieldFilter($query, 'created_by_admin');
//        $this->fieldFilter($query, 'updated_by_admin');
        $this->fieldFilter($query, 'address', 'like');

        $this->fieldFilter($query, 'title', 'like');
        $this->fieldFilter($query, 'custom_name', 'like');
        $this->fieldFilter($query, 'custom_mobile', 'like');

        if ($this->county_id) {
            $query->joinWith([
                'county' => function(ActiveQuery $builder) {
                    $builder->andFilterWhere(['like', 'merger_name', $this->county_id]);
                },
            ]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => ['defaultOrder' => ['id' => SORT_DESC, ]],
        ]);
        if (!$this->validate()) {
            return $dataProvider;
        }
        return $dataProvider;
    }
}
